<?php
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2016/6/7
 * Time: 11:47
 */
class CouponAction extends Action
{
    //优惠券方案列表
    public function couponSchemeList($name = '', $start = 0, $limit = 10)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $couponScheme = M("module_coupon_scheme");
        Session::switchCustomer($customerId);
        $where['a.cId'] = array("eq", $customerId);
        $where['a.deleted'] = array("eq", 0);
        $where['a.name'] = array("like", "%$name%");
        $arr = $couponScheme->alias("a")
            ->join("wx_module_coupon b on a.id=b.schemeId and b.deleted=0")
            ->where($where)
            ->field("a.id,a.name,a.receiveType,a.status,a.isDefault,sum(b.copiesNum) as copiesNum,sum(b.money*b.copiesNum) as money,
            sum(b.surplusNum) as surplusNum,sum(b.money*b.surplusNum) as surplusMoney,a.updateTime")
            ->limit($start, $limit)
            ->group("a.id")
            ->order("a.updateTime desc")
            ->select();
        if ($arr) {
             foreach ($arr as $key=>$value){
                $url = R('MiContent/getH5ServerHost');
                $url .= "call.html?customerId=".$customerId."&module=product&method=sendCouponToUser&params=%7B%22schemeId%22:".$value['id'].",%22status%22:".$value['status']."%7D";
                $arr[$key]['url'] = $url;
                $url = '';
            }
            $count = $couponScheme->alias("a")->where($where)->count();
            Output::instance()->objArray($arr, $count);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //导出二维码
    public function exportQrcode($id,$num){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $couponScheme = M("module_coupon_scheme");
        $schemeExport = M("module_coupon_scheme_export");
        $couponModel = M("module_coupon");
        Session::switchCustomer($customerId);
        $schemeInfo = $couponScheme->alias("a")
            ->join("wx_module_coupon b on a.id=b.schemeId and b.deleted=0")
            ->where("a.id=$id")
            ->field("a.*,max(b.surplusNum) as surplusNum")
            ->group("a.id")
            ->find();
        if($schemeInfo['surplusNum']<$num){
            Output::instance()->resultCode(1,"优惠券数量不足");
            return;
        }
        $count = $schemeExport->where("schemeId=$id")->count();
        $couponList = $couponModel->where("schemeId=$id")->field("surplusNum,money")->select();
        $totalMoney = 0;
        foreach($couponList as $key=>$value){
            if($value['surplusNum']<$num){
                $totalMoney += $value['surplusNum']*$value['money'];
            }else{
                $totalMoney += $value['money']*$num;
            }
        }
        if($schemeInfo['codeType']==0){
            $qrType = QR_LIMIT_SCENE;
        }else{
            $qrType = QR_SCENE;
        }
        $path=LOCAL_PIC_PATH . "couponcode/";
        for($i=0;$i<$num;$i++){
            $serialNumber = $count.(10000+$i);
            $data = QRCode::add("优惠券" .$schemeInfo['name'].$serialNumber, null,"product", $id, "scanCouponCode",$qrType, '', '', $customerId);
            $qrImg = $data["img"];
            self::createImage($path,$serialNumber,$qrImg,$schemeInfo['qrcodeBack'],$schemeInfo['qrcodeLocation'],$schemeInfo['qrcodeSize']);
        }
        $result = self::getIDZip($path,"coupon_code_".time().".zip");
        if($result->path){
            $data['cid']=$customerId;
            $data['schemeId']=$id;
            $data['num']=$num;
            $data['totalPrice']=$totalMoney;
            $data['fileUrl']=$result->path;
            $data['createTime']=date("Y-m-d H:i:s");
            $result = $schemeExport->add($data);
            Output::instance()->object($data);
        }else{
            Output::instance()->resultCode();
        }

    }
    public function createImage($path,$fileName,$qrImg,$bgImgUrl,$location,$size){
        $fname="$fileName.png";
        if(!file_exists($path)){
            mkdir ($path);
        }
        $fileName=$path . "$fname";
        $img=self::curls($bgImgUrl);
        $img=imagecreatefromstring($img);
        if(!$img) {
            $out1 = new stdClass();
            $out1->code=1;
            $out1->msg="背景图片获取错误，请重试";
            return $out1;
        }
        $imgWidth=imagesx($img);
        $imgHeight=imagesy($img);
        $qrImg=self::curls($qrImg);
        $qrImg=imagecreatefromstring($qrImg);
        if(!$qrImg) {
            $out1=new StdClass();
            $out1->code=1;
            $out1->msg="二维码生成错误，请重试";
            return $out1;
        }
        $qrImgWidth=imagesx($qrImg);
        $qrImgHeight=imagesy($qrImg);
        if($size){
            $size = explode("*",$size);
            $sizeW = $size[0];
            $sizeH = $size[1];
        }else{
            $sizeW=220;
            $sizeH=220;
        }
        if($location){
            $location = explode("|",$location);
            $qrImgLeft=$location[0];
            $qrImgTop=$location[1];
        }else{
            $qrImgLeft=$imgWidth/2-110;
            $qrImgTop = $imgHeight/2-110;
        }
        imagecopyresampled($img,$qrImg,$qrImgLeft,$qrImgTop,0,0,$sizeW,$sizeH,$qrImgWidth,$qrImgHeight);
        imagejpeg($img,$fileName);
        imagedestroy($img);
    }
    public function curls($url, $timeout = '10')
    {
        // 1. 初始化
        $ch = curl_init();
        // 2. 设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 3. 执行并获取HTML文档内容
        $info = curl_exec($ch);
        // 4. 释放curl句柄
        curl_close($ch);

        return $info;
    }
    public function getIDZip($path,$filename){
        $zip = new ZipArchive(); // 使用本类，linux需开启zlib，windows需取消php_zip.dll前的注释
        if($zip->open($path.$filename, ZIPARCHIVE::CREATE)=== TRUE){
            self::addFileToZip($path, $zip); //调用方法，对要打包的根目录进行操作，并将ZipArchive的对象传递给方法
            $zip->close(); //关闭处理的zip文件
        }

        if(file_exists($path.$filename)){
            $out=R("Upload/uploadLocalZipToOss",array($filename,$path.$filename));
            self::removeDir($path);
            if(!$out->code){
                return $out;
            }
        }
//        header('Content-type: application/force-download');
//        header('Content-Disposition: attachment; filename='.basename($filename));
//        @readfile($filename);
//        unlink($filename);
    }
    private function removeDir($dirName)
    {
        if(! is_dir($dirName))
        {
            return false;
        }
        $handle = @opendir($dirName);
        while(($file = @readdir($handle)) !== false)
        {
            if($file != '.' && $file != '..')
            {
                $dir = $dirName . '/' . $file;
                is_dir($dir) ? self::removeDir($dir) : @unlink($dir);
            }
        }
        closedir($handle);
        return rmdir($dirName) ;
    }
    private function addFileToZip($path,$zip){
        $handler=opendir($path); //打开当前文件夹由$path指定。
        while(($filename=readdir($handler))!==false){
            if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’，不要对他们进行操作
                if(is_dir($path."/".$filename)){// 如果读取的某个对象是文件夹，则递归
                    addFileToZip($path."/".$filename, $zip);
                }else{ //将文件加入zip对象
                    $zip->addFile($path."/".$filename,$filename);
                }
            }
        }
        @closedir($path);
    }
    //设置默认或启用 删除
    public function setCouponSchemeById($id, $status = 0, $isDefault = 0, $deleted = 0)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $couponScheme = M("module_coupon_scheme");
        Session::switchCustomer($customerId);
        if ($isDefault == 1) {
            $couponScheme->where("isDefault=1 and deleted=0")->setField("isDefault", 0);
        }
        $where["id"] = array("eq", $id);
        $data['deleted'] = $deleted;
        $data['status'] = $status;
        $data['isDefault'] = $isDefault;
        $data['updateTime'] = date("Y-m-d H:i:s");
        $result = $couponScheme->where($where)->save($data);
        if ($result !== false) {
            Output::instance()->resultCode();
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    //优惠券方案详情
    public function getCouponSchemeById($id)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $couponScheme = M("module_coupon_scheme");
        Session::switchCustomer($customerId);
        $where["a.id"] = array("eq", $id);
        $couponSchemeInfo = $couponScheme->alias("a")
            ->join("wx_".$customerId."_material b on a.newsId=b.id")
            ->field("a.*,b.xml")
            ->where($where)->find();
        if($couponSchemeInfo['config']){
            $couponSchemeInfo['config']=json_decode($couponSchemeInfo['config'],true);
        }
        if($couponSchemeInfo['qrcodeLocation']){
            $qrcodeLocation = explode("|",$couponSchemeInfo['qrcodeLocation']);
            $couponSchemeInfo['codeLocationX'] = $qrcodeLocation[0];
            $couponSchemeInfo['codeLocationY'] = $qrcodeLocation[1];
        }
        if($couponSchemeInfo['qrcodeSize']){
            $qrcodeSize = explode("*",$couponSchemeInfo['qrcodeSize']);
            $couponSchemeInfo['codeSizeX'] = $qrcodeSize[0];
            $couponSchemeInfo['codeSizeY'] = $qrcodeSize[1];
        }
        Output::instance()->object($couponSchemeInfo);
    }

    //保存优惠卷方案
    public function saveCouponScheme($name, $status,$receiveType, $shareTitle, $shareImg, $shareDescribe, $isEffective,
                                     $startTime, $endTime, $accOrderPrice, $minPrice, $accProductTags, $productTags,
                                     $config,$id = null,$qrcodeBack=null,$qrcodeLocation=null,$qrcodeSize=null,$newsId=null,$codeType=null)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $couponScheme = M("module_coupon_scheme");
        Session::switchCustomer($customerId);
        $data['name'] = $name;
        $data['cId'] = $customerId;
        $data['status'] = $status;
        $data['receiveType'] = $receiveType;
        $data['shareTitle'] = $shareTitle;
        $data['shareImg'] = $shareImg;
        $data['shareDescribe'] = $shareDescribe;
        $data['isEffective'] = $isEffective;
        $data['startTime'] = $startTime;
        $data['endTime'] = $endTime;
        $data['accOrderPrice'] = $accOrderPrice;
        $data['minPrice'] = $minPrice;
        $data['accProductTags'] = $accProductTags;
        $data['productTags'] = $productTags;
        $data['config']=$config;
        $data['codeType']=$codeType;
        $data['updateTime'] = date("Y-m-d H:i:s");
        isset($qrcodeBack)?$data['qrcodeBack']=$qrcodeBack:"";
        isset($qrcodeLocation)?$data['qrcodeLocation']=$qrcodeLocation:"";
        isset($qrcodeSize)?$data['qrcodeSize']=$qrcodeSize:"";
        isset($newsId)?$data['newsId']=$newsId:"";
        if ($id) {
            $couponScheme->where("id=$id")->save($data);
        } else {
            $data['createTime'] = date("Y-m-d H:i:s");
            $couponScheme->add($data);
        }
        Output::instance()->resultCode();
    }
    //优惠券导出记录
    public function schemeExportList($id,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $schemeExport = M("module_coupon_scheme_export");
        Session::switchCustomer($customerId);
        $where['schemeId']=array("eq",$id);
        $where['cid']=array("eq",$customerId);
        $arr = $schemeExport->where($where)->limit($start,$limit)->order("createTime desc")->select();
        if($arr){
            $count = $schemeExport->where($where)->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode();
        }
    }
    //优惠券方案下的列表
    public function couponListBySchemeId($id, $name = '', $start = 0, $limit = 10)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $couponModel = M("module_coupon");
        Session::switchCustomer($customerId);
        $where['schemeId'] = array("eq", $id);
        $where["deleted"] = array("eq", 0);
        $where['name'] = array("like", "%$name%");
        $arr = $couponModel->where($where)
            ->limit($start, $limit)->order("updateTime desc")->select();
        if ($arr) {
            $count = $couponModel->where($where)->count();
            Output::instance()->objArray($arr, $count);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    //删除优惠券
    public function deletedCouponById($id)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $couponModel = M("module_coupon");
        Session::switchCustomer($customerId);
        $data['deleted'] = 1;
        $data['updateTime'] = date("Y-m-d H:i:s");
        $result = $couponModel->where("id=$id")->save($data);
        if ($result !== false) {
            Output::instance()->resultCode();
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    //优惠券详情
    public function couponById($id)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $couponModel = M("module_coupon");
        Session::switchCustomer($customerId);
        $result = $couponModel->where("id=$id")->find();
        $result['usedNum'] = $result['copiesNum'] - $result['surplusNum'];
        if ($result) {
            Output::instance()->object($result);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    //保存优惠券
    public function saveCoupon($schemeId, $name, $money, $copiesNum, $isEffective,
                               $startTime, $endTime, $accOrderPrice, $minPrice, $accProductTags,
                               $productTags,$recommend,$id = null)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $couponModel = M("module_coupon");
        Session::switchCustomer($customerId);
        $data['name'] = $name;
        $data['schemeId'] = $schemeId;
        $data['money'] = $money;
        $data['copiesNum'] = $copiesNum;
        $data['isEffective'] = $isEffective;
        $data['startTime'] = $startTime;
        $data['endTime'] = $endTime;
        $data['accOrderPrice'] = $accOrderPrice;
        $data['minPrice'] = $minPrice;
        $data['accProductTags'] = $accProductTags;
        $data['productTags'] = $productTags;
        $data['recommend']=$recommend;
        $data['updateTime'] = date("Y-m-d H:i:s");
        if ($id) {
            $couponInfo = $couponModel->where("id=$id")->find();
            $surplusNum = $copiesNum - $couponInfo['copiesNum'] + $couponInfo['surplusNum'];
            $data['surplusNum'] = $surplusNum;
            $couponModel->where("id=$id")->save($data);
        } else {
            $data['surplusNum'] = $copiesNum;
            $data['createTime'] = date("Y-m-d H:i:s");
            $couponModel->add($data);
        }
        Output::instance()->resultCode();
    }

    //复制优惠券
    public function copyCouponById($id)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $couponModel = M("module_coupon");
        Session::switchCustomer($customerId);
        $couponInfo = $couponModel->where("id=$id")->find();
        unset($couponInfo['id']);
        $couponInfo['surplusNum'] = $couponInfo['copiesNum'];
        $couponInfo['createTime'] = date("Y-m-d H:i:s");
        $couponInfo['updateTime'] = date("Y-m-d H:i:s");
        $result = $couponModel->add($couponInfo);
        if ($result) {
            Output::instance()->object($result);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    //派发统计
    public function couponSend($id, $start = 0, $limit = 10)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $couponSend = M("module_coupon_send");
        Session::switchCustomer($customerId);
        $where['a.cId'] = array("eq", $customerId);
        $where['a.schemeId'] = array("eq", $id);
        $arr = $couponSend->alias("a")
            ->join("inner join wx_" . $customerId . "_user_weixin_info b on a.openid=b.openid")
            ->where($where)
            ->field("a.*,b.nickname,b.headimgurl")
            ->limit($start, $limit)
            ->order("a.createTime desc")
            ->select();
        if ($arr) {
            $count = $couponSend->alias("a")
                ->join("inner join wx_" . $customerId . "_user_weixin_info b on a.openid=b.openid")
                ->where($where)
                ->count();
            Output::instance()->objArray($arr, $count);
        } else {
            $result['total'] = 0;
            $result['results'] = [];
            Output::instance()->object($result);
        }
    }

    //派发详情
    public function couponSendDetail($id, $start = 0, $limit = 10)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $couponSendDetail = M("module_coupon_send_detail");
        Session::switchCustomer($customerId);
        $where['a.sendId'] = array("eq", $id);
        $where["b.cId"]=array("eq",$customerId);
        $where["d.deleted"]=array("eq",0);
        $arr = $couponSendDetail->alias("a")
            ->join("inner join wx_module_user_coupon b on a.id=b.sendDetailId")
            ->join("inner join wx_module_coupon d on b.couponId=d.id")
            ->join("wx_".$customerId."_user_weixin_info c on b.openid=c.openid")
            ->where($where)
            ->field("b.*,d.name,c.nickname,c.headimgurl,d.money")
            ->limit($start, $limit)
            ->order("a.createTime desc")
            ->select();
        if ($arr) {
            $count = $couponSendDetail->alias("a")
                ->join("inner join wx_module_user_coupon b on a.id=b.sendDetailId")
                ->join("inner join wx_module_coupon d on b.couponId=d.id")
                ->join("wx_".$customerId."_user_weixin_info c on b.openid=c.openid")
                ->where($where)
                ->count();
            Output::instance()->objArray($arr, $count);
        } else {
            Output::instance()->resultCode();
        }
    }
}